<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      ></el-alert>
      <el-steps :active="active - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form
        ref="addFormRef"
        :model="addForm"
        label-width="80px"
        label-position="top"
        :rules="addFormRules"
      >
        <el-tabs
          tab-position="left"
          v-model="active"
          :before-leave="beforeLeave"
          @tab-click="tabClick"
        >
          <el-tab-pane name="0" label="基本信息">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" required>
              <el-cascader
                v-model="select_Cat"
                :options="options"
                :props="{
                  expandTrigger: 'hover',
                  label: 'cat_name',
                  value: 'cat_id',
                }"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="1" label="商品参数">
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyTableData"
              :key="item.attr_id"
            >
              {{ item }}
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="attr"
                  v-for="(attr, key) in item.attr_vals"
                  :key="key"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="2" label="商品属性">
            <el-form-item
              :label="item.attr_name"
              :key="item.attr_id"
              v-for="item in onlyTableData"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="3" label="商品图片">
            <el-upload
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headerObj"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane name="4" label="商品内容">
            <quill-editor ref="myQuillEditor" v-model="addForm.goods_introduce"/>
            <el-button type="primary" class="btnAdd" size="small" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览弹窗 -->
    <el-dialog
      title="查看图片"
      :visible.sync="previewDialogVisible"
      width="50%"
    >
      <img :src="previewUrl" alt="" width="100%">
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      active: "0",
      addForm: {
        goods_name: "",
        goods_price: "",
        goods_weight: "",
        goods_number: "",
        goods_cat: "",
        pics: [],
        goods_introduce: "",
        attrs: []
      },
      addFormRules: {
        goods_name: [
          { required: true, message: "请输入商品名称！", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格！", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量！", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量！", trigger: "blur" },
        ],
      },

      //分类数据
      options: [],
      //选择的分类
      select_Cat: [],
      manyTableData: [],
      onlyTableData: [],
      uploadURL: "http://timemeetyou.com:8889/api/private/v1/upload",
      headerObj: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      //图片预览 控制
      previewDialogVisible: false,
      //图片预览地址
      previewUrl: "",
    };
  },
  created() {
    this.getCategory();
  },
  methods: {
    async getCategory() {
      const { data: res } = await this.$http.get("/categories");
      if (res.meta.status !== 200)
        return this.$message.error("获取分类列表失败！");
      this.options = res.data;
      console.log(res.data);
    },
    handleChange(value) {
      if (value.length !== 3) {
        return (this.select_Cat = []);
      }
      this.addForm.goods_cat = this.select_Cat.join(",");
    },
    beforeLeave(active, oldActive) {
      if (oldActive == 0 && this.select_Cat == "") {
        this.$message.info("请先添加商品分类！");
        return false;
      }
    },
    async tabClick() {
      if (this.active == 1) {
        const {
          data: res,
        } = await this.$http.get(
          `categories/${this.select_Cat[2]}/attributes`,
          { params: { sel: "many" } }
        );
        if (res.meta.status !== 200)
          return this.$message.error("获取参数列表失败！");
        res.data.forEach((item, key) => {
          item.attr_vals = item.attr_vals.split(",");
        });
        this.manyTableData = res.data;
      } else if (this.active == 2) {
        const {
          data: res,
        } = await this.$http.get(
          `categories/${this.select_Cat[2]}/attributes`,
          { params: { sel: "only" } }
        );
        console.log(res);
        if (res.meta.status !== 200)
          return this.$message.error("获取参数列表失败！");
        this.onlyTableData = res.data;
      }
    },
    //图片预览
    handlePreview(file) {
      console.log(file);
      this.previewUrl = file.response.data.url;
      this.previewDialogVisible = true;
    },
    //图片删除
    handleRemove(file) {
      let path = file.response.data.tmp_path;
      let index = this.addForm.pics.findIndex((item) => item.pic == path);
      this.addForm.pics.splice(index, 1);
      console.log(index);
      console.log(this.addForm);
    },
    //上传成功钩子事件
    handleSuccess(response) {
      let picInfo = { pic: response.data.tmp_path };
      this.addForm.pics.push(picInfo);
    },
    //添加商品
    add(){
      this.$refs.addFormRef.validate(async value => {
        if(!value){
          this.$message.error("请填写表单必需项！");
          return false;
        }else{
          //添加动态参数，动态参数数组转字符串
         this.manyTableData.forEach(item => {
           let tmpObj = {attr_id: item.attr_id, attr_value: item.attr_vals.join(",")};
           this.addForm.attrs.push(tmpObj);
         });
         //添加静态参数
         this.onlyTableData.forEach(item => {
           let tmpObj = {attr_id: item.attr_id, attr_value: item.attr_vals}
           this.addForm.attrs.push(tmpObj);
         });
         //发起请求，添加商品
         const {data: res} = await this.$http.post("goods", this.addForm);
         console.log(res);
         if(res.meta.status == 400){return this.$message.error("商品名称已存在！")}
         else if(res.meta.status != 201){return this.$message.error("商品添加失败！")}
         this.$message.success("商品添加成功！");
         this.$router.push("/goods");
        }
      });
    }
  },
};
</script>

<style lang="less" scoped>
.el-steps {
  margin-top: 15px;
}
.el-tabs {
  margin-top: 20px;
}
.el-form-item {
  margin-left: 20px;
}

.el-checkbox {
  margin: 0px 10px 0px 0px;
}
.btnAdd{
  margin-top: 15px;
}
</style>